<?php

namespace app\common\model\user;

use app\common\exception\Exception;
use app\common\library\Email;
use app\common\model\GoodsTag;
use app\common\model\Hospital;
use app\common\model\MedicalInfo;
use app\common\model\order\Order;
use app\common\model\order\OrderItem;
use app\common\model\UserCards;
use think\Db;
use think\Model;


class Appoints extends Model
{

    

    

    // 表名
    protected $name = 'user_appoints';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'is_send_text'
    ];

    public $checkinfoList = ['预约中','预约成功','预约失败'];
    
    public function getIsSendList()
    {
        return ['0' => __('Is_send 0'), '1' => __('Is_send 1'), '2' => __('Is_send 2')];
    }


    public function getIsSendTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_send']) ? $data['is_send'] : '');
        $list = $this->getIsSendList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function business()
    {
        return $this->belongsTo(Business::class, 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function hospital()
    {
        return $this->belongsTo('app\common\model\Hospital', 'hisptial_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function cards()
    {
        return $this->belongsTo('Cards', 'card_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function info()
    {
        return $this->belongsTo('app\common\model\user\medical\Info', 'medical_info_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function saveAppionts($params)
    {
        $data['code']=400;
        $data['msg']='预约失败1';
        if(!empty($params['id'])){
            $is_apooint =$this->where(['user_id'=>$params['user_id'],'id'=>$params['id']])->find();
            if(!$is_apooint){
               // \Exception('不存在该预约');
                $data['msg']='不存在该预约';
                return $data;
            }

        }

        $card = (new UserCards())->where(['user_id'=>$params['user_id'],'id'=>$params['card_id']])->find();
        if(!$card){
       //     \Exception('不存在该权益');
            $data['msg']='不存在该权益';
            return $data;
        }
        if($card['rights_endtime']<=time()){
            $data['msg']='权益已过期';
            return $data;
        }
        if($card['can_uses']<1){
            $data['msg']='权益使用完毕';
            return $data;
        }
        if($card['order_item_id']>0){
            $orderitem=(new OrderItem())->where(['id'=>$card['order_item_id']])->find();
            if($orderitem['refund_status']==1){
               // \Exception('已申请退款不可预约');
                $data['msg']='已申请退款不可预约';
                return $data;
            }
            if($orderitem['refund_status']==2){
             //   Exception('已退款不可预约');
                $data['msg']='已退款不可预约';
                return $data;
            }
        }

        $info =(new MedicalInfo())->where(['id'=>$params['info_id'],'user_id'=>$params['user_id']])->find();
        if(!$info){
            Exception('不存在该姓名');
        }
        Db::startTrans();
        $tags_name=db('user_card_examines')->where(['id'=>$params['tags_id']])->value('tag_name');
        $hospital=(new Hospital())->where(['id'=>$params['hosptial_id']])->find();
        $appoint_time=explode('-',$params['appoint_times']);
        $saves=['user_id'=>$params['user_id'],
            'appoint_mobile'=>$params['appoint_mobile'],
            'hisptial_id'=>$params['hosptial_id'],
            'appoint_week_name'=>$params['appoint_week_name'],
            'hisptials_name'=>$hospital['hospital_name'],
            'appoint_time'=>strtotime($params['appoint_date']),
            'appoint_text'=>$params['appoint_text'],
            'appoint_date'=>$params['appoint_date'],
            'appoint_times'=>$params['appoint_times'],
            'business_id'=>$card['business_id'],
            'appoint_startime'=>strtotime($params['appoint_date'].$appoint_time[0]),
            'appoint_endtime'=>strtotime($params['appoint_date'].$appoint_time[1]),
            'hisptials'=>json_encode($hospital),
            'rights_title'=>$card['rights_title'],
            'rights_memo'=>$card['rights_memo'],
            'rights_card'=>$card['rights_card'],
            'order_id'=>$card['order_id'],
            'birthday'=>$info['medical_birth'],
            'order_item_id'=>$card['order_item_id'],
            'card_id'=>$params['card_id'],
            'medical_info_id'=>$params['info_id'],
            'username'=>$info['medical_username'],
            'card_no'=>$info['medical_cardno'],
            'gender'=>$info['medical_gender'],
            'rights_tags'=>$card['rights_tags'],
            'tag_id'=>$params['tags_id'],
            'tag_text'=>$tags_name,
            'createtime'=>time(),
            'updatetime'=>time(),

        ];
        GoodsTag::where(['id'=>$params['tags_id']])->setInc('appoints');

            if($card['can_uses']==1){
                (new UserCards())->where(['id'=>$params['card_id']])->update(['status'=>2]);
                Order::where(['id'=>$card['order_id']])->update(['status'=>2,'order_status'=>2]);
            }
            (new UserCards())->where(['id'=>$params['card_id']])->setDec('can_uses');
            (new UserCards())->where(['id'=>$params['card_id']])->setInc('used_nums');
            Order::where(['id'=>$card['order_id']])->setDec('canuse_appoints');
            Order::where(['id'=>$card['order_id']])->setInc('used_appoints');
            OrderItem::where(['id'=>$card['order_item_id']])->setDec('canuse_num');
            OrderItem::where(['id'=>$card['order_item_id']])->setInc('used_num');

            $res = $this->insertGetId($saves);





          if($res){
              Db::commit();
              $data['code']=200;
              $data['msg']='预约成功';
              $config = get_addon_config('alisms');
              $template='SMS_463160557';
              $sign = '新眼光';
              $mobile=$params['appoint_mobile'];
              $param=['name'=>$info['medical_username']];
              $alisms = new \addons\alisms\library\Alisms();
              $ret = $alisms->mobile($mobile)
                  ->template($template)
                  ->sign($sign)
                  ->param($param)
                  ->send();

              if ($ret) {
                  (new Appoints())->where(['id'=>$res])->update(['is_send'=>1]);

              } else {
                  (new Appoints())->where(['id'=>$res])->update(['is_send'=>2]);

              }
              $kefus=db('kefu')->where(['status'=>1])->select();
              $email =new Email();
              foreach ($kefus as $k=>$e){
                  if($e['email']){
                      $subject = '你收到一封新的邮件！';
                      $content= '您好！名为'.$info['medical_username'].'的客户已经在本平台上预约，请立刻登录新眼光健康管理后台，对其预约进行处理。谢谢!';
                      $result = $email->to($e['email'])
                          ->subject($subject)
                          ->message($content)
                          ->send();
                  }
                  if($e['mobile']){
                      $template='SMS_463650801';
                      $sign = '新眼光';
                      $mobile=$e['mobile'];
                      $param=['name'=>$info['medical_username']];
                      $alisms = new \addons\alisms\library\Alisms();
                      $ret = $alisms->mobile($mobile)
                          ->template($template)
                          ->sign($sign)
                          ->param($param)
                          ->send();
                  }
              }



           ;
          }else{
              Db::rollback();
          }



        return $data;
    }

    public function updateAppionts($params)
    {
        $data['code']=400;
        $data['msg']='改约失败';
        $is_apooint =$this->where(['user_id'=>$params['user_id'],'id'=>$params['id']])->find();
        if(!$is_apooint){
            // \Exception('不存在该预约');
            $data['msg']='不存在该预约';
            return $data;
        }


        Db::startTrans();

        $appoint_time=explode('-',$params['appoint_times']);
        $saves=[
            'appoint_week_name'=>$params['appoint_week_name'],

            'appoint_time'=>strtotime($params['appoint_date']),
            'appoint_text'=>$params['appoint_text'],
            'appoint_date'=>$params['appoint_date'],
            'appoint_times'=>$params['appoint_times'],
            'appoint_startime'=>strtotime($params['appoint_date'].$appoint_time[0]),
            'appoint_endtime'=>strtotime($params['appoint_date'].$appoint_time[1]),


        ];
        $res=$params['id'];
        $saves['id']=$params['id'];
        (new Appoints())->isUpdate(true)->save($saves);

        if($res){
            $data['code']=200;
            $data['msg']='改约成功';
            Db::commit();
            $config = get_addon_config('alisms');
            $template='SMS_463681493';
            $sign = '新眼光';
            $mobile=$is_apooint['appoint_mobile'];
            $param=['name'=>$is_apooint['username']];
            $alisms = new \addons\alisms\library\Alisms();
            $ret = $alisms->mobile($mobile)
                ->template($template)
                ->sign($sign)
                ->param($param)
                ->send();

            if ($ret) {
                (new Appoints())->where(['id'=>$res])->update(['is_send'=>1]);

            } else {
                (new Appoints())->where(['id'=>$res])->update(['is_send'=>2]);

            }
            $kefus=db('kefu')->where(['status'=>1])->select();
            $email =new Email();
            foreach ($kefus as $k=>$e){
                if($e['email']){
                    $subject = '你收到一封新的邮件！';
                    $content= '您好！名为'.$is_apooint['username'].'的客户在本平台修改了其预约，请立刻登录新眼光健康管理后台，对其改约进行处理。谢谢！';
                    $result = $email->to($e['email'])
                        ->subject($subject)
                        ->message($content)
                        ->send();
                }
                if($e['mobile']){
                    $template='SMS_463611518';
                    $sign = '新眼光';
                    $mobile=$e['mobile'];
                    $param=['name'=>$is_apooint['username']];
                    $alisms = new \addons\alisms\library\Alisms();
                    $ret = $alisms->mobile($mobile)
                        ->template($template)
                        ->sign($sign)
                        ->param($param)
                        ->send();
                }
            }

        }else{
            Db::rollback();
        }



        return $data;
    }
}
